//
//  CashierNewViewController.m
//  TryShopping
//
//  Created by LiYinDi on 16/6/3.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "scanViewController.h"
#import "HasSpecFmdbTool.h"
#import "NoSpecFmdbTool.h"
#import "HasSpecFmdbModel.h"
#import "NoSpecFmdbModel.h"
#import "CashierNewDataModel.h"
#import "SelectedGoodNewViewController.h"
#import "CashierNewPopView.h"
#import "CashierNewSearchViewController.h"
#import "RapidCashierViewController.h"
#import "GatheringListViewController.h"
#import "PlaceOrderViewController.h"
#import "OrderExtAddViewController.h"
#import "MembershipDetailsViewController.h"
#import "OrderDetailViewController.h"
#import "fmDataModel.h"
#import "WhsInAddViewController.h"
#import "StockManagementViewController.h"
#import "MemberListViewController.h"
#import "OrderListViewController.h"
#import "ToBindCompanyViewController.h"
#import "MsgPlaySound.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MCouponBViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
#import "SelectedGoodNewViewController1.h"
#import "ReabamSingleton.h"
@interface scanViewController ()<CashierNewPopViewDelegate,CashierNewSearchDelegate,MCouponBViewControllerDelegate>
{
    
    NSString *Token;
    CashierNewDataModel *cashierModel;
    NSString *titleStr;
    NSString *scanTypeStr;
    NSString*specIdStr;
    NSMutableArray*scanConponResultArray;
    NSMutableArray*snList;
    NSString * result1;
    ReabamSingleton*commdity;
}
@property (retain, nonatomic) UIAlertView* alt;
@end

@implementation scanViewController

-(void)viewDidLoad
{
    
    [super viewDidLoad];
    scanConponResultArray=[[NSMutableArray alloc]init];
    snList=[[NSMutableArray alloc]init];

}

-(void)update:(NSString *)updateData{
    [scanConponResultArray removeAllObjects];
    [snList removeAllObjects];
    scanConponResultArray=[[NSMutableArray alloc]init];
    snList=[[NSMutableArray alloc]init];

}
-(void)viewWillAppear:(BOOL)animated
{
    commdity=[ReabamSingleton shared];
    self.memberDict=commdity.dataMemberDict;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
       
    _scanResultStr=@"";
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=YES;
    
    Token = [user objectForKey:@"tokenId"];
  
    _titleLabel.text=@"扫一扫";
    
    [self setAutoLayout];
    [self setScan];
    

    
}


- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}

#pragma mark recover the location of the view
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
}

-(void)setScan
{
    isDown=NO;
    if (_captureSession!=nil) {
        [_captureSession stopRunning];
        [_videoPreviewLayer removeFromSuperlayer];
        _captureSession = nil;
    }
    if (_timer==nil) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
        
        [self startRead];
    }
    [self.view bringSubviewToFront:_bgImageView
     ];
    [self.view bringSubviewToFront:_topView
     ];
    
    [self.view bringSubviewToFront:_scanBottomView
     ];
    [self.view bringSubviewToFront:_ScanLeftView
     ];
    [self.view bringSubviewToFront:_scanTopView
     ];
    [self.view bringSubviewToFront:_scanRightView
     ];

    [self.view bringSubviewToFront:_lineFrameImage
     ];
    [self.view bringSubviewToFront:_lineLabel
     ];
    [self.view bringSubviewToFront:_specNameLabel
     ];
       [self.view bringSubviewToFront:_lineImage
     ];
    
}
-(void)lineAnimation
{
    
    if (isDown==NO) {
        num++;
        [_lineImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
            make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
            make.height.equalTo(@10);
            make.top.equalTo(_lineFrameImage.mas_top).with.offset(2*num);
        }];
        if (2*num+10>=_lineFrameImage.frame.size.height) {
            isDown=YES;
        }
    }
    else
    {
        num--;
        [_lineImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
            make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
            make.height.equalTo(@10);
            make.top.equalTo(_lineFrameImage.mas_top).with.offset(2*num);
        }];
        
        if (num==0) {
            isDown=NO;
        }
    }
    
}

-(BOOL)startRead
{
    
    NSError *error;
    
    AVCaptureDevice *captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        return NO;
    }
    _captureSession = [[AVCaptureSession alloc] init];
    if ([_captureSession canAddInput:input]) {
        [_captureSession addInput:input];
    }
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    captureMetadataOutput.rectOfInterest=self.view.frame;
    if ([_captureSession canAddOutput:captureMetadataOutput]) {
        [_captureSession addOutput:captureMetadataOutput];
    }
    
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    captureMetadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code];
    
    [ captureMetadataOutput setRectOfInterest : CGRectMake (( 154 )/ ScreenHeight ,(( ScreenWidth - 250 )/ 2 )/ ScreenWidth , 250 / ScreenHeight , 250 / ScreenWidth )];

//    [captureMetadataOutput setRectOfInterest:_lineFrameImage.bounds];
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:CGRectMake(0, 0,ScreenWidth,ScreenHeight)];
    [_videoPreviewLayer setBackgroundColor:(__bridge CGColorRef)[Global parseColor:@"#66000000"]];
    [self.view.layer addSublayer:_videoPreviewLayer];
    [_captureSession startRunning];
    return YES;
}
-(void)stopReading{
    
    [_captureSession stopRunning];
    _captureSession = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}

- (void)play
{
    
    sound = kSystemSoundID_Vibrate;//震动
    //    NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"jbl_confirm",@"caf"];
    //    OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
    AudioServicesPlaySystemSound(sound);
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
            [_captureSession stopRunning];
            _captureSession = nil;
            [_timer invalidate];
            _timer=nil;
            [self play];
        
            [self performSelectorOnMainThread:@selector(loadItemDetail) withObject:nil waitUntilDone:NO];
 
        
    }
}

-(void)loadItemDetail
{
    
    [self performSelector:@selector(load) withObject:nil afterDelay:1];

    
}

-(void)load{

    [self.delegate scanGoodInfoData:stringValue];
    [self.navigationController popViewControllerAnimated:YES];

}

-(void)setAutoLayout
{
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@64) ;
        make.top.equalTo(self.view.mas_top);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_topView.mas_centerX);
        make.height.equalTo(@30);
        make.width.equalTo(@52);
        make.top.equalTo(_topView.mas_top).with.offset(25);
    }];
    
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.left.equalTo(_topView.mas_left);
    }];
    
    [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(_topView.mas_bottom);
        make.height.equalTo(@255);
    }];
    [_scanTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(_topView.mas_bottom);
        make.height.equalTo(@120);
    }];
    [_scanBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.equalTo(@255);
    }];
    [_ScanLeftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.width.equalTo(@30) ;
        make.bottom.equalTo(_scanBottomView.mas_top);
        make.top.equalTo(_scanTopView.mas_bottom);
    }];
    [_scanRightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right);
        make.width.equalTo(@30) ;
        make.bottom.equalTo(_scanBottomView.mas_top);
        make.top.equalTo(_scanTopView.mas_bottom);
    }];
    [_lineFrameImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_ScanLeftView.mas_right).with.offset(-7);
        make.right.equalTo(_scanRightView.mas_left).with.offset(7);
        make.bottom.equalTo(_scanBottomView.mas_top).with.offset(7);
        make.top.equalTo(_scanTopView.mas_bottom).with.offset(-7);
    }];
    [_lineImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
        make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
        make.height.equalTo(@10);
        make.top.equalTo(_lineFrameImage.mas_top);
    }];
    
    
    
    
}
- (IBAction)backAction:(id)sender {
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    //    NSLog(@"-------%@",scanTypeStr);
    //    if ([scanTypeStr isEqualToString:@""]) {
    //        
    //        
    //    }else{
    [self.navigationController popViewControllerAnimated:YES];
    [[self rdv_tabBarController]setSelectedIndex:0];
    //    }
}

- (void)showAlertMessage:(NSString *)msg
{
    _alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [_alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:0.5f];
}
- (void)hideAlert
{
    if (_alt != nil)
    {
        [_alt dismissWithClickedButtonIndex:0 animated:YES];
        _alt = nil;
    }
}
@end
